/**
 * WordSetImport.java [V 1.0.0]
 * classes : org.xiaocq.wordsgod.io.WordSetImport
 * xiaocq Create at 2012-6-23 下午9:30:42
 */
package org.xiaocq.wordsgod.io;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

import android.content.Context;

/**
 * org.xiaocq.wordsgod.io.WordSetImport
 * @author Mystory
 * Create at 2012-6-23 下午9:30:42
 */
public class FileIOHelper {
	private Context context;
	
	public FileIOHelper(Context context){
		this.context = context;
	}
	
	/**
	 * 获得一个关于assets文件中文件的缓冲读入流
	 * @param fileName
	 * @return
	 * @throws IOException
	 */
	public BufferedReader getBufferedReaderFromAssets(String fileName) throws IOException{
		BufferedReader reader = wrapStreamToBuffer(context.getAssets().open(fileName));
		
		return reader;
	}
	
	/**
	 *向指定文件名的文件中写入数据 
	 * @param fileName
	 * @param wordScoreList
	 * @return
	 */
	public boolean saveToFile(String fileName, int[] wordScoreList){
		String encoding = "UTF-8";
		int length = wordScoreList.length;
		
		try{
			BufferedWriter writer = wrapStreamToBuffer(getOutputStreamToFile(fileName));
			
			for(int i = 0; i < length; i++){
				if(wordScoreList[i] != 0){
					writer.write(Integer.toString(wordScoreList[i]));
					writer.newLine();
				}
			}
			
			writer.flush();
			writer.close();
		}catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		
		return true;
	}
	
	public int[] getWordScoreList(String fileName, int arraySize) {
		int[] wordScoreList = null;
		String encoding = "UTF-8";
		int index = 0;
		
		try{
			BufferedReader reader = wrapStreamToBuffer(getInputStreamFromFile(fileName));
			
			while(reader.ready()){
				wordScoreList[index++] = Integer.valueOf(reader.readLine());
			}
			
			reader.close();
		}catch (Exception e) {
			e.printStackTrace();
		}
		
		return wordScoreList;
	}
	
	private InputStream getInputStreamFromFile(String fileName) throws FileNotFoundException{
		InputStream inputStream = null;
		inputStream = context.openFileInput(fileName);
		
		return inputStream;
	}
	
	private OutputStream getOutputStreamToFile(String fileName) throws FileNotFoundException{
		OutputStream outputStream = null;
		outputStream = context.openFileOutput(fileName, Context.MODE_PRIVATE);
		
		return outputStream;
	}
	
	private BufferedReader wrapStreamToBuffer(InputStream inputStream){
		return new BufferedReader(new InputStreamReader(inputStream));
	}
	
	private BufferedWriter wrapStreamToBuffer(OutputStream outputStream){
		return new BufferedWriter(new OutputStreamWriter(outputStream));
	}
}
